package com.lh.aop;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.lh.entity.User;
import com.lh.util.Configuration;
import com.lh.util.SessionUtil;
/**
 * 监控业务逻辑执行，如果超过 1000 ms 则警告
 * @author liuhui
 * @version 1.0
 * @date 2013-4-5 下午12:28:54
 */
@Aspect
@Component
public class LogAop {
	private Logger slowLog = Logger.getLogger(Configuration.SLOW_LOG);
	private Logger accessLog = Logger.getLogger(Configuration.ACCESS_LOG);

	private static final int SLOW = Configuration.SLOW_TIME;
	
	@Around("execution (* com.lh.biz.impl.*.*(..))") 
	public Object aroundBiz(ProceedingJoinPoint joinPoint) throws Throwable{
		long currentTime = System.currentTimeMillis();
		try{
			return joinPoint.proceed();
		}finally{
			long after = System.currentTimeMillis() ;
			if(after - currentTime > SLOW){
				slowLog.info(joinPoint.getSignature() + " execute use " + (after - currentTime) + " ms!~" );
			}
		}
		
	}
	

	@Around("execution (* com.lh.web.ctrl.*.*(..))") 
	public Object aroundCtrl(ProceedingJoinPoint joinPoint) throws Throwable{
		long currentTime = System.currentTimeMillis();
		try{
			return joinPoint.proceed();
		}finally{
			HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			String ip = request.getHeader("X-Real-IP");
			if(StringUtils.isBlank(ip)){
				ip = request.getRemoteAddr();
			}
			User user = SessionUtil.getUser();
			long after = System.currentTimeMillis() ;
			accessLog.info("ip:"+ip + " , url=" + request.getRequestURL() + " , use time:" + (after -  currentTime) +"ms" + (user != null ? " , userName=" + user.getUsername() : "") + " , User-Agent:" + request.getHeader("User-Agent") + " , method=" + joinPoint.getSignature()   );
		}
		
	}
	
	
	
	
	
}
